<template>
  <div class="qa-add-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/groups" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">新增群组</h5>
    </div>

    <!-- 群组新增表单 -->
    <div class="group-edit-container">
      <div class="form-container">
        <div class="mb-3">
          <label class="form-label" for="group-name">群组名称</label>
          <input type="text" v-model="group.groupName" id="group-name" class="form-control"
                 :class="{ 'is-invalid': validationErrors.groupName }">
          <div class="invalid-feedback" v-if="validationErrors.groupName">{{ validationErrors.groupName }}</div>
        </div>
        <div class="mb-3">
          <label class="form-label" for="group-description">群组描述</label>
          <textarea v-model="group.groupDescribe" id="group-description" class="form-control"
                    :class="{ 'is-invalid': validationErrors.groupDescribe }"></textarea>
          <div class="invalid-feedback" v-if="validationErrors.groupDescribe">{{ validationErrors.groupDescribe }}</div>
        </div>
        <div class="mb-3">
          <label class="form-label" for="group-members">群成员</label>
          <button @click="showMemberList = !showMemberList" class="btn btn-primary">选择成员</button>
          <div v-if="selectedMembers.length > 0">
            已选择：
            <!-- 这里修改为调用新的方法 -->
            {{ getMemberNamesByIds(selectedMembers) }}
          </div>
          <div class="invalid-feedback2" v-if="validationErrors.selectedMembers">{{validationErrors.selectedMembers }}
          </div>
          <!-- 群成员弹出框 -->
          <div v-if="showMemberList" class="member-list-popup">
            <ul>
              <li v-for="member in memberList" :key="member.userId">
                <label style="display: block; padding: 10px; cursor: pointer;">
                  <input type="checkbox" :value="member.userId" v-model="selectedMembers"
                         :checked="isMemberSelected(member.userId)" @change="updateSelectedName(member)">
                  {{ member.userName }}({{ member.realName }})
                </label>
              </li>
            </ul>
            <button @click="showMemberList = false" class="btn btn-secondary">关闭</button>
          </div>
        </div>
        <div class="mb-3">
          <label class="form-label" for="subject">大学科</label>
          <select v-model="group.dictionaryId" id="subject" class="form-control"
                  :class="{ 'is-invalid': validationErrors.dictionaryId }">
            <option :value="1">英语</option>
            <option :value="2">政治</option>
            <option :value="3">数学</option>
          </select>
          <div class="invalid-feedback" v-if="validationErrors.dictionaryId">{{ validationErrors.dictionaryId }}</div>
        </div>
        <button @click="saveGroup" class="btn btn-primary w-100">保存</button>
      </div>
    </div>
  </div>
</template>

<script>
import CommonLayoutT from "@/components/layout/CommonLayoutT.vue";
import http from "@/router/http";
import router from "@/router/index";

export default {
  name: 'GroupAddView',
  components: {CommonLayoutT},
  data() {
    return {
      group: {
        groupName: '',
        groupDescribe: '',
        dictionaryId: null,
        memberIds: []
      }, // 当前编辑的群组信息
      showMemberList: false, // 控制群成员弹出框的显示与隐藏
      memberList: [], // 成员列表
      selectedMembers: [], // 选中的成员ID列表
      groupId: null, // 群组ID
      existingMemberIds: [], // 存储已有的成员ID
      selectedName: '', // 存储已选择的成员名称
      validationErrors: {
        groupName: '',
        groupDescribe: '',
        selectedMembers: '',
        dictionaryId: ''
      }
    };
  },
  mounted() {
    this.getAllUserList();
  },
  methods: {
    // 获取所有用户列表
    async getAllUserList() {
      try {
        const requestData = {
          role: 1,
          supervision: 1
        }
        const response = await http.post(`/admin/user/getAllUserList`, requestData);
        this.memberList = response.data.response;
      } catch (error) {
        console.error('获取成员列表失败：', error);
      }
    },
    // 保存群组信息
    async saveGroup() {
      this.validationErrors = {
        groupName: '',
        groupDescribe: '',
        selectedMembers: '',
        dictionaryId: ''
      };

      let isValid = true;

      if (!this.group.groupName.trim()) {
        this.validationErrors.groupName = '群组名称不能为空';
        isValid = false;
      }

      if (!this.group.groupDescribe.trim()) {
        this.validationErrors.groupDescribe = '群组描述不能为空';
        isValid = false;
      }

      if (this.selectedMembers.length === 0) {
        this.validationErrors.selectedMembers = '请选择群成员';
        isValid = false;
      }

      if (!this.group.dictionaryId) {
        this.validationErrors.dictionaryId = '请选择大学科';
        isValid = false;
      }

      if (!isValid) {
        return;
      }

      try {
        const requestData = {
          ...this.group,
          memberIds: this.selectedMembers
        };
        const response = await http.put(`/admin/groups/insertOrUpdateGroup`, requestData);
        console.log('群组信息保存成功：', response.data);
        router.push(`/groups`)
        // 保存成功后可以进行一些操作，如跳转页面等
      } catch (error) {
        console.error('保存群组信息失败：', error);
      }
    },
    // 判断成员是否应该被选中
    isMemberSelected(memberId) {
      return this.existingMemberIds.includes(memberId);
    },
    // 更新已选择的成员名称
    updateSelectedName(member) {
      if (this.selectedMembers.includes(member.userId)) {
        this.selectedName = member.userName;
      } else {
        const remainingMembers = this.memberList.filter(m => this.selectedMembers.includes(m.userId));
        if (remainingMembers.length > 0) {
          this.selectedName = remainingMembers[0].userName;
        } else {
          this.selectedName = '';
        }
      }
    },
    // 根据已选择的成员ID更新已选择的成员名称
    updateSelectedNameBasedOnIds() {
      const selectedMembers = this.memberList.filter(m => this.selectedMembers.includes(m.userId));
      if (selectedMembers.length > 0) {
        this.selectedName = selectedMembers[0].userName;
      } else {
        this.selectedName = '';
      }
    },
    // 根据成员ID列表获取成员名称，并用逗号分隔
    getMemberNamesByIds(memberIds) {
      const memberNames = memberIds.map(memberId => {
        const member = this.memberList.find(m => m.userId === memberId);
        return member ? member.userName : '';
      }).filter(name => name !== ''); // 过滤掉空字符串
      return memberNames.join(', ');
    }
  }
};
</script>

<style scoped>
/* 整体布局 */
body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #f0f9f9 0%, #d8e9f9 100%);
  color: #333;
  margin: 0;
  padding: 0;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #00b8a9 0%, #28df99 100%);
  color: white;
  padding: 15px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  margin-bottom: 20px;
}

.header .bi-chevron-left {
  color: white;
  transition: color 0.3s ease;
}

.header .bi-chevron-left:hover {
  color: #d8e9f9;
}

.header h5 {
  font-size: 1.5rem;
  font-weight: 600;
}

/* 群组编辑容器 */
.group-edit-container {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  margin: 20px;
}

/* 表单组样式 */
.form-group {
  margin-bottom: 20px;
}

.form-group label {
  font-size: 1rem;
  color: #555;
  margin-bottom: 10px;
  display: block;
}

.form-control {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 5px;
  transition: border-color 0.3s ease;
}

.form-control:focus {
  border-color: #00b8a9;
  outline: none;
}

/* 无效输入样式 */
.is-invalid {
  border-color: #dc3545;
}

.invalid-feedback {
  color: #dc3545;
  font-size: 0.9rem;
  margin-top: 5px;
}
.invalid-feedback2 {
  color: #dc3545;
  font-size: 0.9rem;
  margin-top: 5px;
}

/* 按钮样式 */
.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #00b8a9 0%, #28df99 100%);
  color: white;
}

.btn-primary:hover {
  background: linear-gradient(135deg, #009688 0%, #21b37f 100%);
}

.btn-secondary {
  background: #ccc;
  color: #333;
}

.btn-secondary:hover {
  background: #bbb;
}

/* 成员列表弹出框 */
.member-list-popup {
  position: absolute;
  background: white;
  padding: 20px;
  border: none;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
  z-index: 999;
}

.member-list-popup ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.member-list-popup li {
  padding: 10px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s ease;
}

.member-list-popup li:hover {
  background: #f0f9f9;
}

.member-list-popup label {
  cursor: pointer;
}

.member-list-popup input[type="checkbox"] {
  margin-right: 10px;
}
</style>